package de.tum.se.sudoku.logic;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import de.tum.se.sudoku.impl.Cell;
import de.tum.se.sudoku.impl.FixedCell;
import de.tum.se.sudoku.impl.Grid;
import de.tum.se.sudoku.impl.VariableCell;

public class SolverRandom implements ISolver {

	/**
	 * This solver tries to guess a solution randomly
	 * Caution: More than six missing values might take a looong time
	 */
	@Override
	public Grid solve(Grid input) {
		Random rnd = new Random();
		Cell[][] cells = input.getCells();
		
		Grid result = new Grid(cells);
		Set<Integer> rowSet = new HashSet<Integer>(); //To ensure that every line only contains the numbers 1-9
		
		while(!input.isValid()) {
			rowSet = new HashSet<Integer>();
			for(int i=0; i<=8; i++) { //row-loop
				for(Cell cell : cells[i]) {
					if (cell instanceof FixedCell)
						rowSet.add(cell.getValue());
				}
				
				for(int j=0; j<=8; j++) {
					if (cells[i][j] instanceof VariableCell) {
						int num = 0;
						num = (rnd.nextInt(9)+1);
						while(rowSet.contains(num)) {
							num = (rnd.nextInt(9)+1);
						}
						rowSet.add(num);
						cells[i][j] = new VariableCell(num);
					}
				}
				
				rowSet = new HashSet<Integer>();
			}
			new Grid(cells).printGrid();
		}
		result = new Grid(cells);
		return result;
	}

}
